package com.sujeet.activity.tracker.model.access;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.sujeet.activity.tracker.model.*;
public class ActivityCrudUtils {
	
	private static final String PERSISTENCE_UNIT_NAME = "activity";
	private EntityManagerFactory factory;
	
	public ActivityCrudUtils() {
		factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
	}
	
	public boolean createOneActivity(double estimatedEffort, Date startDate, String changeLog) {
		Activity activity = new Activity();
		activity.setEstimatedEffort(estimatedEffort);
		activity.setStartDate(startDate);
		activity.setChangeLog(changeLog);
		return createOneActivity(activity);
	}
	
	public boolean createOneActivity(Activity activity) {
		boolean result = false;
		EntityManager em = factory.createEntityManager();
		try {
			em.getTransaction().begin();
			em.persist(activity);		
			em.getTransaction().commit();
			result = true;
		} finally {
			em.close();
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<Activity> getAllActivityEntries() {
		EntityManager em = factory.createEntityManager();
		List<Activity> activityEntries = new ArrayList<Activity>();
		try {
			Query q = em.createQuery("select a from Activity a");
			activityEntries = (List<Activity>) q.getResultList();
		} finally {
			em.close();
		}
		return activityEntries;
	}
	public boolean deleteOneActivity(int id) {
		boolean result = false;
		EntityManager em = factory.createEntityManager();
		try {
			em.getTransaction().begin();
			Query q = em.createQuery("SELECT a FROM Activity a WHERE a.id = :id");
			q.setParameter("id", id);
			Activity activity = (Activity) q.getSingleResult();
			em.remove(activity);		
			em.getTransaction().commit();
			result = true;
		} finally {
			em.close();
		}
		return result;
	}
}
